import { Global, Logger, Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from './common/config/config.module';
import { LogsModule } from './common/logger/logs.module';
import { RedisModule } from '@nestjs-modules/ioredis';
import { ConfigService } from '@nestjs/config';
import { CacheModule } from '@nestjs/cache-manager';
import { redisStore } from 'cache-manager-ioredis-yet';
import { MailService } from './common/mail/mail-service';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { UserModule } from '@/modules/user/user.module';
import { AuthModule } from '@/modules/auth/auth.module';
import { BookModule } from '@/modules/book/book.module';
import { RolesModule } from './modules/roles/roles.module';
import { MenuModule } from './modules/menu/menu.module';

@Global() // 将AppModule设置为全局模块，这样就可以在其他模块中使用AppModule中的服务了
@Module({
  imports: [
    ConfigModule,
    LogsModule,
    CacheModule.register({
      ttl: 30 * 1000, // seconds
      store: redisStore, // cache-manager集成ioredis
      host: 'localhost',
      port: 6379,
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        return {
          type: configService.get('DB'),
          host: configService.get('DB_HOST'),
          port: configService.get('DB_PORT'),
          username: configService.get('DB_USERNAME'),
          password: configService.get('DB_PASSWORD'),
          database: configService.get('DB_DATABASE'),
          entities: [__dirname + '/**/*.entity{.ts,.js}'],
          synchronize: true, // 自动根据entity创建表
          autoLoadEntities: true, // 自动加载entity实例
          logging: process.env.NODE_ENV !== 'production', // 开发阶段打印sql日志
        } as TypeOrmModuleOptions;
      },
    }),
    UserModule,
    AuthModule,
    BookModule,
    MenuModule,
    RolesModule,
    // RedisModule.forRootAsync({
    //   inject: [ConfigService],
    //   useFactory: (configService: ConfigService) => {
    //     // console.log(configService.get('DB_HOST'));
    //     return {
    //       type: 'single',
    //       url: 'localhost:6379',
    //     };
    //   },
    // }),
  ],
  controllers: [AppController],
  providers: [AppService, Logger, MailService],
  exports: [Logger, MailService],
})
export class AppModule {}
